#include "bt_thread.h"
unsigned int bt_thread::sum_index = 0;

#ifdef WIN32
#include <WinSock2.h>
#include <windows.h>
#include <process.h>

//windows32 ʵ�����еĺ���
unsigned int __stdcall one_thread(void * args);
unsigned int __stdcall one_thread(void * args)
{   
    struct thread_evnets * pevent = (struct thread_evnets *)args;
    bt_thread *p = (bt_thread *)(pevent->pthread);
    void *parg = pevent->arg;
    delete pevent;

    PTHREADFUN ppfun = p->funpoint;
    ppfun(parg);
    return 0;
}
#endif

#ifdef LINUX
#include <pthread.h>
#include <unistd.h>
#endif
#include <stdio.h>

bt_thread::bt_thread()
{
    sum_index++;
    this->index = sum_index;
    funpoint = NULL;
}

bt_thread::~bt_thread()
{
    ;
}

void bt_thread::set_fun(PTHREADFUN a)
{
    funpoint = a;
}

bool bt_thread::running(void * arg)
{
    bool result = false;
    if(funpoint)
    {
        
#ifdef WIN32
        struct thread_evnets *tmpevent = new struct thread_evnets;
        tmpevent->arg =arg;
        tmpevent->pthread = (void *)this;
        {   
            if (_beginthreadex (0,0, one_thread, (void *)(tmpevent), 0, NULL) == NULL)
            {   
                //printf("CreateThread() failed with error %d\n", GetLastError());
                return 0;

            }
            else
            {   
                //printf("CreateThread() success thread %d\n",0);
            }
        }
#endif
        
#ifdef LINUX
        int status = 0;
        pthread_t one_thread_t;
        pthread_attr_t attr;
        
        pthread_attr_init(&attr);
        pthread_attr_setstacksize(&attr, 5 * 1024 * 1024);
        
        status = pthread_create(&one_thread_t, &attr, funpoint, arg); // ��һ���߳ƽ�������
        if(0 == status)
        {
            //printf(" pthread  created \n");
        }
        else
        {
            perror(" pthread  create fail\n");
            return 0;
        }
#endif
    }
    return result;
}

void sleep_s(int hou, int min, int sec, int msec)
{
    long long second = hou * 3600 + min * 60 + sec;
    second = second * 1000 + msec;
    
#ifdef WIN32
    (void)::SleepEx(second, true);
#endif
#ifdef LINUX
    second = second * 1000;
    second = second * 1000;
    
    struct timespec req = { 0 };
    req.tv_sec = second / 1000000000;
    
    req.tv_nsec = second % 1000000000;
    //printf("%lld %d   %d \n",second, req.tv_sec,  req.tv_nsec);
    
    nanosleep(&req, NULL);
#endif
    
}

